const {
	Service
} = require('uni-cloud-router')
const uniPay = require('uni-pay');
/**
 * 支付宝、微信支付处理，不能直接调用
 */
module.exports = class UniPayService extends Service {
	constructor(ctx) {
		super(ctx)
	}
	/**
	 * 创建支付订单
	 */
	async app(order, userInfo) {
		let config = this.ctx.getConfigs.paymentConfigs(this.type)
		// console.log("app config",config)
		let uniPayIns = uniPay[config["uniPay"]](config);
		//获取微信/支付宝小程序openid
		let openid = this.getOpenid(userInfo);
		let requestOptions = {
			openid, //支付宝小程序、微信小程序必填
			subject: order.body.substr(0, 20), // 微信支付时不可填写此项
			body: order.body.substr(0, 30),
			outTradeNo: order.outTradeNo, //订单号
			totalFee: order.total_fee, // 金额，单位分
			notifyUrl: order.notifyUrl // 支付结果通知地址
		}
		//微信服务商模式https://pay.weixin.qq.com/wiki/doc/api/jsapi_sl.php?chapter=9_1
		if (config.sub_mch_id) {
			let params = Object.assign(requestOptions, {
				sub_mch_id: config.sub_mch_id,
			});
			if (config.sub_appid) {
				if (openid) {
					params.sub_openid = openid;
				}
				params.sub_appid = config.sub_appid;
			} else {
				params.openid = openid;
			}
			console.log("params", params);
			const orderResult = await uniPayIns.unifiedOrder(params)
			if (!orderResult.prepayId) {
				throw new Error(orderResult.errMsg || '获取prepayId失败')
			}
			console.log("orderResult", orderResult);
			//以子商户appid发起支付
			if (config.sub_appid) {
				uniPayIns.options.appId = config.sub_appid;
			}
			const payParams = uniPayIns._getPayParamsByPrepayId(
				orderResult.prepayId,
				params.signType || uniPayIns.options.signType
			)
			console.log("params", params);
			return Object.assign(orderResult, payParams)
		} else {
			//普通模式//支付宝小程序、微信小程序必填
			requestOptions.openid = openid;
			// console.log("uniPayIns",uniPayIns)
			return await uniPayIns.getOrderInfo(requestOptions);
		}
	}
	/**
	 *  验证
	 *  https://uniapp.dcloud.io/uniCloud/unipay?id=%e6%94%af%e4%bb%98%e7%bb%93%e6%9e%9c%e9%80%9a%e7%9f%a5%e5%a4%84%e7%90%86
	 */
	async verify(config, event, next) {
		await next(res);
		return true;
	}

	/**
	 * 资金退款，定时处理
	 * @param {Object} order 退款订单
	 */
	async refund(order) {
		console.log(order)
		delete order.payInfo;
		delete order.uid;
		let config = this.ctx.getConfigs.paymentConfigs(this.type, order.platform)
		delete order.platform;
		let uniPayIns = uniPay[config["uniPay"]](config);
		let payName = this.payname;
		//微信服务商模式
		if (config.sub_mch_id) {
			order.sub_mch_id = config.sub_mch_id;
			if (config.sub_appid) {
				order.sub_appid = config.sub_appid;
			}
		}
		try {
			let res = await uniPayIns.refund(order);
			console.log("unipay refund", JSON.stringify(res));
			return `退款将退回至您的${payName}账户，请注意查收`;
		} catch (e) {
			console.log("unipay refund 退款失败");
			console.log(JSON.stringify(e))
		}
		return false;
	}

	getOpenid(userInfo) {}
}
